//
//  CitiesListView.m
//  YGYTechnology
//
//  Created by 袁庭楷 on 2018/11/14.
//  Copyright © 2018年 YGY. All rights reserved.
//

#import "CitiesListView.h"
#import "ProvinceModel.h"
#import "TMXCityModel.h"
#import "CitiesListCell.h"
#import "Tool.h"

#pragma mark - 定义字号
#define kFont(X)     [UIFont systemFontOfSize:X]
#define kNameFont(Name, X)   [UIFont fontWithName:Name size:X]

#define __kColorMY__ 0x3C6CFC
#define __kPageTextBg__ 0x666666
#define __kUnSelectedBtnBg__ 0x999999
#define __kSelectedBtnBg__ 0x4C3428

@interface CitiesListView()<UITableViewDelegate,UITableViewDataSource, UIGestureRecognizerDelegate>
@property (nonatomic, strong) UITableView *provinceTableView;
@property (nonatomic, strong) UITableView *cityTableView;
@property (nonatomic, strong) UITableView *areaTableView;
@property (nonatomic, strong) UIView * coverView;
@property (nonatomic, strong) NSMutableArray *provinceArray;//数据源（全局）
@property (nonatomic, strong) NSIndexPath * provinceIndexPath;
@property (nonatomic, strong) NSIndexPath * cityIndexPath;
@property (nonatomic, strong) NSIndexPath * areaIndexPath;
@property (nonatomic, strong) UIButton * provinceBtn;//省 按钮
@property (nonatomic, strong) UIButton * cityBtn;//城市 按钮
@property (nonatomic, strong) UIButton * areaBtn;//区域 按钮
@property (nonatomic, strong) UIView * provinceLine;//省 下面的线
@property (nonatomic, strong) UIView * cityLine;//城市 下面的线
@property (nonatomic, strong) UIView * areaLine;//区域 下面的线
@property (nonatomic, strong) NSString * PCAString;//省城市区域
@end

@implementation CitiesListView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    _provinceArray = [NSMutableArray array];
    [self loadRequestData];
    [self createUI];
    return self;
}

-(void)createUI{
    
    self.coverView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    self.coverView.backgroundColor = [UIColor colorWithHex:333333];
    self.coverView.alpha = 0.5;
    UIGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(coverViewTouchUpInside)];
    tapGesture.delegate = self;
    [self.coverView addGestureRecognizer:tapGesture];
    [self addSubview:self.coverView];
    
    UIView *bgView = [UIView new];
    bgView.userInteractionEnabled = YES;
    bgView.layer.cornerRadius = 8;
    bgView.backgroundColor = [UIColor whiteColor];
    [self addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(0);
        make.left.offset(0);
        make.right.offset(0);
        make.height.mas_offset(451);
    }];
    
    UILabel *topLabel = [self newWithText:@"请选择" fontSize:18 textColor:[UIColor colorWithHex:333333] textAlignment:NSTextAlignmentCenter];
    [bgView addSubview:topLabel];
    [topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgView);
        make.top.offset(14);
    }];
    
    UIView *lineView = [UIView new];
    lineView.backgroundColor = [Tool colorWithHexString:@"EEEEEE"];
    [bgView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_offset(1);
        make.top.equalTo(topLabel.mas_bottom).offset(14);
        make.left.offset(12);
        make.right.offset(-12);
    }];
    
    UIButton *cancelBtn = [UIButton new];
    [cancelBtn setImage:[UIImage imageNamed:@"clear_icon"] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(clickCancelBtn) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-11);
        make.top.offset(11);
        make.height.width.offset(26);
    }];
    
    NSInteger btnTotalSize = 0;
    for (int i = 0; i < 3; i++) {
        UIButton *btn = [UIButton new];
        [btn setBackgroundColor:[UIColor clearColor]];
        btn.titleLabel.font = kFont(16);
        [btn setTitleColor:[Tool UIColorFromRGB:333333] forState:UIControlStateNormal];
        btn.hidden = YES;
        [btn setTitle:@"请选择" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(selectBtn:) forControlEvents:UIControlEventTouchUpInside];
        CGSize btnTextSize = [btn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName : kFont(16)}];
        btnTotalSize = btnTotalSize + btnTextSize.width;//所有文字总和
        NSInteger priorSize = btnTotalSize - btnTextSize.width;//前几个按钮的文字总和
        [bgView addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(12 + priorSize + 26 * i);
            make.top.equalTo(lineView.mas_bottom).offset(12);
            make.width.offset(btnTextSize.width);
            make.height.offset(btnTextSize.height + 10);
        }];
        
        UIView *bottomLineView = [UIView new];
        bottomLineView.hidden = YES;
        bottomLineView.backgroundColor = [Tool colorWithHexString:@"EEEEEE"];
        [btn addSubview:bottomLineView];
        [bottomLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_offset(1);
            make.width.offset(btnTextSize.width);
            make.centerX.equalTo(btn);
            make.bottom.offset(0);
        }];
        
        switch (i) {
            case 0:
                self.provinceBtn = btn;
                self.provinceBtn.hidden = NO;
                [self.provinceBtn setTitleColor:[Tool colorWithHexString:@"FA2D1A"] forState:UIControlStateNormal];
                self.provinceLine = bottomLineView;
                self.provinceLine.hidden = YES;
                [self showProvince];
                break;
            case 1:
                self.cityBtn = btn;
                self.cityLine = bottomLineView;
                break;
            case 2:
                self.areaBtn = btn;
                self.areaLine = bottomLineView;
                break;
        }
    }
    
    [bgView addSubview:self.provinceTableView];
    [bgView addSubview:self.cityTableView];
    [bgView addSubview:self.areaTableView];
}
- (UILabel *)newWithText:(NSString *)text fontSize:(CGFloat)fontSize textColor:(UIColor *)textColor textAlignment:(NSTextAlignment)textAlignment {
    UILabel *new = [UILabel new];
    new.text = text;
    new.numberOfLines = 0;
    new.font = kFont(fontSize);
    new.textColor = textColor;
//    new.lineBreakMode = NSLineBreakByTruncatingTail;
    new.textAlignment = textAlignment;
    return new;
}
#pragma mark ------------------ 点击省 城市 区域 --------
-(void)selectBtn:(UIButton *)sender{
    
    if (sender == self.provinceBtn) {
        [self showProvince];
    }else if (sender == self.cityBtn){
        [self showCity];
    }else if (sender == self.areaBtn){
        [self showArea];
    }
}

-(void)showProvince{//显示省
    self.provinceTableView.hidden = NO;
    self.cityTableView.hidden = YES;
    self.areaTableView.hidden = YES;
    self.provinceLine.hidden = NO;
    self.cityLine.hidden = YES;
    self.areaLine.hidden = YES;
    [self.provinceBtn setTitleColor:[Tool UIColorFromRGB:__kColorMY__] forState:UIControlStateNormal];
    [self.cityBtn setTitleColor:[Tool UIColorFromRGB:__kPageTextBg__] forState:UIControlStateNormal];
    [self.areaBtn setTitleColor:[Tool UIColorFromRGB:__kPageTextBg__] forState:UIControlStateNormal];
}

-(void)showCity{//显示城市
    self.provinceTableView.hidden = YES;
    self.cityTableView.hidden = NO;
    self.areaTableView.hidden = YES;
    self.provinceLine.hidden = YES;
    self.cityLine.hidden = NO;
    self.areaLine.hidden = YES;
    [self.provinceBtn setTitleColor:[Tool UIColorFromRGB:__kPageTextBg__] forState:UIControlStateNormal];
    [self.cityBtn setTitleColor:[Tool UIColorFromRGB:__kColorMY__] forState:UIControlStateNormal];
    [self.areaBtn setTitleColor:[Tool UIColorFromRGB:__kPageTextBg__] forState:UIControlStateNormal];
}

-(void)showArea{//显示区域
    self.provinceTableView.hidden = YES;
    self.cityTableView.hidden = YES;
    self.areaTableView.hidden = NO;
    self.provinceLine.hidden = YES;
    self.cityLine.hidden = YES;
    self.areaLine.hidden = NO;
    [self.provinceBtn setTitleColor:[Tool UIColorFromRGB:__kPageTextBg__] forState:UIControlStateNormal];
    [self.cityBtn setTitleColor:[Tool UIColorFromRGB:__kPageTextBg__] forState:UIControlStateNormal];
    [self.areaBtn setTitleColor:[Tool UIColorFromRGB:__kColorMY__] forState:UIControlStateNormal];
}

- (void)loadRequestData{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"TMXCity" ofType:@"json"];
    NSError *error;
    NSString *fileString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        return;
    }
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSArray *arrayCityList  = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    //    省级数组
    for (NSDictionary *provinceDic in arrayCityList) {
        ProvinceModel *provinceModel = [[ProvinceModel alloc]initWithDictionary:provinceDic];
        [_provinceArray addObject:provinceModel];
    }
}

#pragma mark  -------tableview代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([tableView isEqual:self.provinceTableView]) {
        return _provinceArray.count;
    }else if ([tableView isEqual:self.cityTableView]){
        ProvinceModel *p = _provinceArray[self.provinceIndexPath.row];
        CityArrayModel *cArray = p.citiesListModel;
        return cArray.citiesArray.count;
    }else  if ([tableView isEqual:self.areaTableView]){
        ProvinceModel *p = _provinceArray[self.provinceIndexPath.row];
        TMXCityModel *c = p.citiesListModel.citiesArray[self.cityIndexPath.row];
        return c.areaListArray.count;
    }else{
        return  0;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return 0.0001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([tableView isEqual:self.provinceTableView]) {
        CitiesListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"provinceListCell"];
        if (cell == nil) {
            cell = [[CitiesListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"provinceListCell"];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        ProvinceModel *p = _provinceArray[indexPath.row];
        cell.leftLabel.text = p.province;
        if (indexPath == self.provinceIndexPath) {//第一次进来 无勾选状态
            cell.iconImage.hidden = NO;
            cell.leftLabel.textColor = [Tool UIColorFromRGB:__kColorMY__];
            [self.provinceBtn setTitle:p.province forState:UIControlStateNormal];
            CGSize btnTextSize = [p.province sizeWithAttributes:@{NSFontAttributeName : kFont(16)}];
            
            [self.provinceBtn mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_offset(btnTextSize.width + 10);
            }];
            [self.provinceLine mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_offset(btnTextSize.width);
            }];
        }else{
            cell.leftLabel.textColor = [Tool UIColorFromRGB:__kPageTextBg__];
            cell.iconImage.hidden = YES;
        }
        return cell;
    }else if ([tableView isEqual:self.cityTableView]){
        CitiesListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cityListCell"];
        if (cell == nil) {
            cell = [[CitiesListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cityListCell"];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        ProvinceModel *p = _provinceArray[self.provinceIndexPath.row];
        CityArrayModel *cArray = p.citiesListModel;
        cell.leftLabel.text = cArray.citiesArray[indexPath.row].city;
        if (indexPath == self.cityIndexPath) {//第一次进来 无勾选状态
            cell.iconImage.hidden = NO;
            cell.leftLabel.textColor = [Tool UIColorFromRGB:__kColorMY__];
            [self.cityBtn setTitle:cArray.citiesArray[indexPath.row].city forState:UIControlStateNormal];
            [self textHeightAndWidth:self.cityBtn and:self.cityLine];
            
        }else{
            cell.iconImage.hidden = YES;
            cell.leftLabel.textColor = [Tool UIColorFromRGB:__kPageTextBg__];
        }
        return cell;
    }else  if ([tableView isEqual:self.areaTableView]){
        CitiesListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"areaListCell"];
        if (cell == nil) {
            cell = [[CitiesListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"areaListCell"];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        ProvinceModel *p = _provinceArray[self.provinceIndexPath.row];
        TMXCityModel *c = p.citiesListModel.citiesArray[self.cityIndexPath.row];
        cell.leftLabel.text = c.areaListArray[indexPath.row].name;
        
        if (indexPath == self.areaIndexPath) {//第一次进来 无勾选状态
            cell.iconImage.hidden = NO;
            cell.leftLabel.textColor = [Tool UIColorFromRGB:__kColorMY__];
            [self.areaBtn setTitle:c.areaListArray[indexPath.row].name forState:UIControlStateNormal];
            [self textHeightAndWidth:self.areaBtn and:self.areaLine];
            //最终选定的地区
            self.PCAString = [NSString stringWithFormat:@"%@%@%@",p.province,c.city,c.areaListArray[self.areaIndexPath.row].name];
            NSString *code = [NSString stringWithFormat:@"%@,%@,%@",p.pcode,c.ccode,c.areaListArray[self.areaIndexPath.row].acode];
            NSString *address = [NSString stringWithFormat:@"%@,%@,%@",p.province,c.city,c.areaListArray[self.areaIndexPath.row].name];
            self.PACStr(self.PCAString, code, address);
            [self coverViewTouchUpInside];
        }else{
            cell.iconImage.hidden = YES;
            cell.leftLabel.textColor = [Tool UIColorFromRGB:__kPageTextBg__];
        }
          cell.userInteractionEnabled = YES;
        if ([self checkISChoose:c.areaListArray[indexPath.row].acode]) {
            cell.leftLabel.textColor = [Tool UIColorFromRGB:__kUnSelectedBtnBg__];
            cell.userInteractionEnabled = NO;
        }
        return cell;
    }
    return nil;
}
- (BOOL) checkISChoose:(NSString *)code{
    NSSet *set = [NSSet setWithArray:self.purchasedSource];
    for (NSDictionary *dic in set) {
        if ([code isEqualToString:dic[@"district_code"]]) {
            return YES;
        }
    }
    return NO;
}

-(CGSize)textHeightAndWidth:(UIButton *)btn and:(UIView *)lineView{
    CGSize btnTextSize = [btn.titleLabel.text sizeWithAttributes:@{NSFontAttributeName : kFont(16)}];
    [btn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(btnTextSize.width + 10);
    }];
    [lineView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset(btnTextSize.width);
    }];
    return btnTextSize;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if ([tableView isEqual:self.provinceTableView]) {
        self.provinceIndexPath = indexPath;
        self.cityIndexPath = nil;
        self.areaIndexPath = nil;
        self.cityBtn.hidden = NO;
        self.areaBtn.hidden =YES;
        [self.cityBtn setTitle:@"请选择" forState:UIControlStateNormal];
        [self textHeightAndWidth:self.cityBtn and:self.cityLine];
        [self showCity];
         ProvinceModel *p = _provinceArray[indexPath.row];
        CGSize btnTextSize = [p.province sizeWithAttributes:@{NSFontAttributeName : kFont(16)}];
        [self.cityBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.offset(btnTextSize.width + 15);
        }];
    }else if ([tableView isEqual:self.cityTableView]){
        self.cityIndexPath = indexPath;
        self.areaIndexPath = nil;
        self.areaBtn.hidden = NO;
        [self.areaBtn setTitle:@"请选择" forState:UIControlStateNormal];
        [self textHeightAndWidth:self.cityBtn and:self.areaLine];
        [self showArea];
        ProvinceModel *p = _provinceArray[self.provinceIndexPath.row];
        TMXCityModel *c = p.citiesListModel.citiesArray[self.cityIndexPath.row];
        CGSize btnTextSize = [c.city sizeWithAttributes:@{NSFontAttributeName : kFont(16)}];
        [self.areaBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.offset(btnTextSize.width + self.cityBtn.mj_x + 15);
        }];
    }else  if ([tableView isEqual:self.areaTableView]){
        self.areaIndexPath = indexPath;
    }
    [self.provinceTableView reloadData];
    [self.cityTableView reloadData];
    [self.areaTableView reloadData];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}
#pragma mark  -------初始化tableview
-(UITableView *)provinceTableView {
    if (!_provinceTableView) {
        _provinceTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 95, ScreenWidth, 451 - 95) style:UITableViewStyleGrouped];
        _provinceTableView.delegate = self;
        _provinceTableView.dataSource = self;
//        _provinceTableView.allowsSelection = NO;
        _provinceTableView.userInteractionEnabled = YES;
        _provinceTableView.showsVerticalScrollIndicator = NO;
        _provinceTableView.showsHorizontalScrollIndicator = NO;
        _provinceTableView.backgroundColor = [UIColor clearColor];
        _provinceTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _provinceTableView;
}

-(UITableView *)cityTableView{
    if (!_cityTableView) {
        _cityTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 95, ScreenWidth - 28, 451 - 95) style:UITableViewStyleGrouped];
        _cityTableView.delegate = self;
        _cityTableView.dataSource = self;
//        _cityTableView.allowsSelection = NO;
        _cityTableView.showsVerticalScrollIndicator = NO;
        _cityTableView.showsHorizontalScrollIndicator = NO;
        _cityTableView.backgroundColor = [UIColor clearColor];
        _cityTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _areaTableView.hidden = YES;
    }
    return _cityTableView;
}

- (UITableView *)areaTableView{
    if (!_areaTableView) {
        _areaTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 95, ScreenWidth - 28, 451 - 95) style:UITableViewStyleGrouped];
        _areaTableView.delegate = self;
        _areaTableView.dataSource = self;
//        _areaTableView.allowsSelection = NO;
        _areaTableView.showsVerticalScrollIndicator = NO;
        _areaTableView.showsHorizontalScrollIndicator = NO;
        _areaTableView.backgroundColor = [UIColor clearColor];
        _areaTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _areaTableView.hidden = YES;
    }
    return _areaTableView;
}

//蒙层点击手势
- (void)coverViewTouchUpInside {
    [UIView animateWithDuration:0.25 animations:^{
        self.hidden = YES;
        [self removeAllSubviews];
    }completion:^(BOOL finished) {
    }];
}
-(void)clickCancelBtn{
    [self coverViewTouchUpInside];
}
@end
